package com.heking.zplayer.qlyopen;

import android.content.Context;
import android.text.TextUtils;

import com.cmcc.qlyopensdk.init.config.header.HeaderManager;
import com.cmcc.qlyopensdk.init.impl.QlyOpenSdk;
import com.cmcc.qlyopensdk.net.HttpManager;
import com.cmcc.qlyopensdk.net.bean.BaseResponse;
import com.cmcc.qlyopensdk.net.callback.NetCallBack;
import com.cmcc.qlyopensdk.net.impl.HttpRequest;
import com.cmcc.qlyopensdk.player.constant.PlayerHD;
import com.cmcc.qlyopensdk.utils.MD5Utils;
import com.cmcc.qlyopensdk.utils.TypeUtils;
import com.cmcc.qlyopensdk.vo.response.CameraAbility;
import com.cmcc.qlyopensdk.vo.response.CameraSettingInfo;
import com.cmcc.qlyopensdk.vo.response.TimeLineSectionBean;
import com.cmcc.vnsdk.camera.restapi.model.response.OpenPlatformToken;
import com.google.gson.JsonObject;

import org.MediaPlayer.PlayM4.Player;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.NonNull;

/**
 * @Author: zhoug
 * @Date: 2024-11-05
 * @Description:
 */
public class QLYApi {
    private static final String BASE_HOST = "https://hoa.and-home.cn/";
    //获取token
    private static final String GET_TOKEN = "v3/open/api/token";
    //获取设备列表
    private static final String GET_DEVICE_LIST = "v3/open/api/device/list";


    private QLYApi() {
    }


    /**
     * 获取token
     *
     * @param tokenInfo
     */
    public static void getOpenPlatformToken(QlyTokenParams tokenInfo, @NonNull Callback<QlyToken> callBack) {
        String sig = sig(tokenInfo.getAppId(), tokenInfo.getSecret());
        JsonObject params = new JsonObject();
        params.addProperty("operatorType", tokenInfo.getOperatorType());
        params.addProperty("action", tokenInfo.getAction());
        params.addProperty("targetType", tokenInfo.getTargetType());
        params.addProperty("target", tokenInfo.getTarget());
        params.addProperty("sig", sig);
        String body = params.toString();
        HttpRequest request = new HttpRequest();
        request.body = body;
        request.url = BASE_HOST + GET_TOKEN;
        request.headers = HeaderManager.getInstance().createHeader(body);
        HttpManager.getInstance().httpsPost(request, new NetCallBack<BaseResponse<OpenPlatformToken>>() {
                    @Override
                    public void onResponse(BaseResponse<OpenPlatformToken> response) {
                        ThreadUtils.runMainThread(()->{
                            if (response.isSuccess()) {
                                QlyToken qlyToken = null;
                                OpenPlatformToken data = response.getData();
                                if (data != null) {
                                    String token = data.getToken();
                                    if (!TextUtils.isEmpty(token)) {
                                        qlyToken = new QlyToken();
                                        qlyToken.setToken(token);
                                        qlyToken.setExpiresIn(data.getExpires_in());
                                    }
                                }
                                if (qlyToken != null) {
                                    callBack.onSuccess(qlyToken);
                                } else {
                                    callBack.onError("没有返回token");
                                }
                            } else {
                                callBack.onError(response.getResultMsg());
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        ThreadUtils.runMainThread(()->{
                            callBack.onError(throwable.getMessage());

                        });
                    }
                },
                TypeUtils.createType(BaseResponse.class, OpenPlatformToken.class));
    }

    /**
     * 获取设备列表
     *
     * @param page
     * @param pageSize
     * @param callBack
     */
    public static void getDeviceList(int page, int pageSize, @NonNull Callback<List<QlyCameraInfoBean>> callBack) {
        JsonObject params = new JsonObject();
        params.addProperty("page", page);
        params.addProperty("pageSize", pageSize);
        String body = params.toString();
        HttpRequest request = new HttpRequest();
        request.url = BASE_HOST + GET_DEVICE_LIST;
        request.body = body;
        request.headers = HeaderManager.getInstance().createHeader(body);
        HttpManager.getInstance().httpsPost(request, new NetCallBack<BaseResponse<List<QlyCameraInfoBean>>>() {
            @Override
            public void onResponse(BaseResponse<List<QlyCameraInfoBean>> response) {
                if (response.isSuccess()) {
                    List<QlyCameraInfoBean> data = response.getData();
                    callBack.onSuccess(data);
                } else {
                    callBack.onError(response.getResultMsg());
                }
            }

            @Override
            public void onError(Throwable throwable) {
                callBack.onError(throwable.getMessage());
            }
        }, TypeUtils.createListType(BaseResponse.class, QlyCameraInfoBean.class));
    }

    protected static String sig(String appId, String secret) {
        return MD5Utils.md5(appId + secret);
    }

    /**
     * 连接设备
     *
     * @param context
     * @param deviceId {@link ZQlyOpenSdk#getMacByDeviceId(String)}
     */
    public static void connectCamera(Context context, String deviceId, @NonNull Callback<String> callback) {
        QlyOpenSdk.getInstance().connect(context, deviceId, new NetCallBack<BaseResponse<String>>() {
            @Override
            public void onResponse(BaseResponse<String> response) {
                if (response.isSuccess()) {
                    ThreadUtils.runMainThread(()->{
                        String data = response.getData();
                        if (!TextUtils.isEmpty(data)) {
                            callback.onSuccess(data);
                        } else {
                            callback.onError("deviceId isEmpty");
                        }
                    });
                } else {
                    ThreadUtils.runMainThread(()->{
                        callback.onError(response.getResultMsg());
                    });
                }
            }

            @Override
            public void onError(Throwable throwable) {
                ThreadUtils.runMainThread(()->{
                    callback.onError(throwable.getMessage());

                });
            }
        });


    }

    public static void disconnect() {
        QlyOpenSdk.getInstance().disconnect();
    }

    /**
     * 获取设备能力
     *
     * @param deviceId {@link ZQlyOpenSdk#getMacByDeviceId(String)}
     */
    public static void getDeviceAbility(String deviceId, @NonNull Callback<CameraAbility> callback) {
        QlyOpenSdk.getInstance().getDeviceAbility(deviceId, new NetCallBack<BaseResponse<CameraAbility>>() {
            @Override
            public void onResponse(BaseResponse<CameraAbility> response) {
                if (response.isSuccess()) {
                    CameraAbility data = response.getData();
                    if (data != null) {
                        ThreadUtils.runMainThread(()->{
                            callback.onSuccess(data);
                        });
                    } else {

                        ThreadUtils.runMainThread(()->{
                            callback.onError("CameraAbility is null");
                        });
                    }
                } else {
                    ThreadUtils.runMainThread(()->{
                        callback.onError(response.getResultMsg());
                    });
                }
            }

            @Override
            public void onError(Throwable throwable) {
                ThreadUtils.runMainThread(()->{
                    callback.onError(throwable.getMessage());

                });
            }
        });
    }

    /**
     * 高标清切换
     *
     * @param deviceId 设备id {@link ZQlyOpenSdk#getMacByDeviceId(String)}
     * @param hd
     * @param callback Integer -1表示切换失败
     */
    public static void switchPlaybackQuality(String deviceId, int hd, @NonNull Callback<Integer> callback) {
        int quality = hd == ZQlyOpenSdk.QUALITY_HD ? PlayerHD.ON : PlayerHD.OFF;
        QlyOpenSdk.getInstance().switchPlaybackQuality(deviceId, quality, new NetCallBack<BaseResponse<?>>() {
            @Override
            public void onResponse(BaseResponse<?> response) {
                if (response.isSuccess()) {
                    ThreadUtils.runMainThread(()->{
                        callback.onSuccess(hd);
                    });
                } else {
                    ThreadUtils.runMainThread(()->{
                        callback.onSuccess(-1);


                    });
                }
            }

            @Override
            public void onError(Throwable throwable) {
                ThreadUtils.runMainThread(()->{
                    callback.onError(throwable.getMessage());

                });
            }
        });
    }

    /**
     * 获取设置信息
     *
     * @param deviceId 设备id {@link ZQlyOpenSdk#getMacByDeviceId(String)}
     * @param callback
     */
    public static void getSettings(String deviceId, @NonNull Callback<QlyCameraSetting> callback) {
        QlyOpenSdk.getInstance().getSettings(deviceId, new NetCallBack<BaseResponse<List<CameraSettingInfo>>>() {
            @Override
            public void onResponse(BaseResponse<List<CameraSettingInfo>> response) {
                if (response.isSuccess()) {
                    List<CameraSettingInfo> data = response.getData();
                    if (data != null && !data.isEmpty()) {
                        ThreadUtils.runMainThread(()->{
                            callback.onSuccess(QlyCameraSetting.create(data.get(0)));
                        });
                    } else {

                        ThreadUtils.runMainThread(()->{
                            callback.onError("没有获取到设置信息");
                        });
                    }
                } else {
                    ThreadUtils.runMainThread(()->{
                        callback.onError(response.getResultMsg());

                    });
                }
            }

            @Override
            public void onError(Throwable throwable) {
                ThreadUtils.runMainThread(()->{
                    callback.onError(throwable.getMessage());

                });
            }
        });
    }


    /**
     * 获取云存储回放数据列表
     *
     * @param deviceId  设备id {@link ZQlyOpenSdk#getMacByDeviceId(String)}
     * @param startTime 开始时间 毫秒
     * @param endTime   结束时间 毫秒
     * @param callback
     */
    public static void getTimelineSectionList(String deviceId, long startTime, long endTime, @NonNull Callback<List<RecordSegment>> callback) {
        QlyOpenSdk.getInstance().getTimelineSectionList(deviceId, startTime, endTime, new NetCallBack<BaseResponse<List<TimeLineSectionBean>>>() {
            @Override
            public void onResponse(BaseResponse<List<TimeLineSectionBean>> response) {
                if (response.isSuccess()) {
                    List<RecordSegment> segments = getRecordSegments(response);
                    ThreadUtils.runMainThread(()->  callback.onSuccess(segments));
                } else {
                    ThreadUtils.runMainThread(()-> callback.onError(response.getResultMsg()));
                }
            }

            @Override
            public void onError(Throwable throwable) {
                ThreadUtils.runMainThread(()-> callback.onError(throwable.getMessage()));
            }
        });
    }

    /**
     * 获取SD卡回放数据列表
     *
     * @param deviceId  设备id {@link ZQlyOpenSdk#getMacByDeviceId(String)}
     * @param startTime 开始时间 毫秒
     * @param endTime   结束时间 毫秒
     * @param callback
     */
    public static void getSdcardTimelineSectionList(String deviceId, long startTime, long endTime, @NonNull Callback<List<RecordSegment>> callback) {
        QlyOpenSdk.getInstance().getTimelineSectionList(deviceId, startTime, endTime, new NetCallBack<BaseResponse<List<TimeLineSectionBean>>>() {
            @Override
            public void onResponse(BaseResponse<List<TimeLineSectionBean>> response) {
                if (response.isSuccess()) {
                    List<RecordSegment> segments = getRecordSegments(response);
                    ThreadUtils.runMainThread(()->{
                        callback.onSuccess(segments);
                    });
                } else {

                    ThreadUtils.runMainThread(()->{
                        callback.onError(response.getResultMsg());
                    });
                }

            }

            @Override
            public void onError(Throwable throwable) {
                ThreadUtils.runMainThread(()->{
                    callback.onError(throwable.getMessage());
                });
            }
        });
    }

    @NonNull
    private static List<RecordSegment> getRecordSegments(BaseResponse<List<TimeLineSectionBean>> response) {
        List<RecordSegment> segments = new ArrayList<>();
        List<TimeLineSectionBean> data = response.getData();
        if (data != null && !data.isEmpty()) {
            for (TimeLineSectionBean item : data) {
                RecordSegment recordSegment = new RecordSegment(item.getStartTime(), item.getEndTime());
                recordSegment.setThumbnailUrl(item.getThumbnailUrl());
                segments.add(recordSegment);
            }
            Collections.sort(segments);
        }
        return segments;
    }

}
